import { ref } from 'vue'
import store from '@/store'
import { defineStore } from 'pinia'
import { useTagsViewStore } from '../system/tags-view'
import { useSettingsStore } from '../system/settings'
import { getToken, removeToken, setToken } from '@/utils/cache/local-token'
import { resetRouter } from '@/router'
import { getUserInfoAPI } from '@/api/login'
import routeSettings from '@/config/route'

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken() || '')
  const roles = ref([])
  const username = ref('')

  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()

  /** 登录存储token */
  const setLocalToken = newToken => {
    setToken(newToken)
    token.value = newToken
  }

  /** 获取用户详情 */
  // const getInfo = async () => {
  //   const { data } = await getUserInfoAPI()
  //   username.value = data.username
  //   // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色 ["admin"] 或 ["developer", "editor"]
  //   roles.value = data.roles?.length > 0 ? data.roles : routeSettings.defaultRoles

  // }
  const getInfo = async () => {
    return new Promise(resolve => {
      const data = {
        username: 'admin',
        roles: ['admin']
      }
      username.value = data.username
      roles.value = data.roles?.length > 0 ? data.roles : routeSettings.defaultRoles
      setTimeout(() => {
        resolve(data)
      }, 500)
    })
  }

  /** 模拟角色变化 */
  const changeRoles = async role => {
    const newToken = 'token-' + role
    token.value = newToken
    setToken(newToken)
    // 用刷新页面代替重新登录
    window.location.reload()
  }

  /** 登出 */
  const logout = () => {
    removeToken()
    token.value = ''
    roles.value = []
    resetRouter()
    _resetTagsView()
  }

  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ''
    roles.value = []
  }

  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  return { token, roles, username, getInfo, changeRoles, logout, resetToken, setLocalToken }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
